package net.jueb.frameworkDemo.orm.mysql.mybatis.typeHandler;

import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@MappedTypes(value = { Set.class,Integer.class})
@MappedJdbcTypes(includeNullJdbcType=true, value = { JdbcType.VARCHAR })
public class CannonsTypeHandler extends BaseTypeHandler<Set<Integer>>{

	private Type type=new TypeToken<List<Integer>>(){}.getType();
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Set<Integer> parameter, JdbcType jdbcType)
			throws SQLException {
		Gson gson=new Gson();
		String json=gson.toJson(parameter,type);
		ps.setString(i,json);
	}

	@Override
	public Set<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String json=rs.getString(columnName);
		if(json!=null)
		{
			Gson gson=new Gson();
			return  gson.fromJson(json, type);
		}
		return null;
	}

	@Override
	public Set<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String json=rs.getString(columnIndex);
		if(json!=null)
		{
			Gson gson=new Gson();
			return  gson.fromJson(json,type);
		}
		return null;
	}

	@Override
	public Set<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String json=cs.getString(columnIndex);
		if(json!=null)
		{
			Gson gson=new Gson();
			return  gson.fromJson(json,type);
		}
		return null;
	}
}
